#include <stdio.h>
#include <string.h>
#include "member.h"


#define MEMBER_INFO_FILE "data/member_info.dat"
#define MEMBER_ID_BASE   100001



static unsigned int get_new_mid(void)
{
	member_info mi;
	unsigned int mid;

	FILE* fp = fopen(MEMBER_INFO_FILE, "rb");

	if(fp == NULL)
	{
		return MEMBER_ID_BASE;
	}

	fseek(fp, -sizeof(mi), SEEK_END);
	
	if(fread(&mi, sizeof(mi), 1, fp) == 1)
	{
		mid = mi.mid + 1;
	}
	else
	{
		mid = MEMBER_ID_BASE;
	}

	fclose(fp);

	return mid;
}


void member_reg(void)
{
	member_info mi;

	printf("请按照如下提示输入会员信息。\n\n");
	printf("卡号：");
	scanf("%s", mi.card_num);
	printf("姓名：");
	scanf("%s", mi.name);
	printf("性别（1-女,2-男）：");
	scanf("%d", (int*)&mi.s);
	printf("手机号：");
	scanf("%s", mi.phone);
	printf("会员类型（1-次卡,2-月卡,3-年卡）：");
	scanf("%d", (int*)&mi.mt);

	if(mi.mt == cika)
	{
		printf("剩余次数：");
		scanf("%d", &mi.remain_cnt);
	}

	mi.reg_time = time(NULL);

	if(mi.mt == yueka)
		mi.expire_time = mi.reg_time + 30 * 24 * 60 * 60;
	else
		mi.expire_time = mi.reg_time + 365 * 24 * 60 * 60;

	mi.mid = get_new_mid();

	FILE* fp = fopen(MEMBER_INFO_FILE, "ab");
	
	if(fp == NULL)
	{
		perror("会员注册失败");
		return;
	}

	fwrite(&mi, sizeof(mi), 1, fp);

	fclose(fp);

	printf("\n注册会员成功！\n");
}


void member_show(void)
{
	member_info mi;
	char card_num[11];

	printf("\n会员请刷卡！\n");
	scanf("%s",card_num);

	FILE* fp = fopen(MEMBER_INFO_FILE, "rb");

	if(fp == NULL)
	{
		printf("\n卡片未注册，请联系工作人员处理！\n");
		return;
	}

	while(fread(&mi, sizeof(mi), 1, fp) == 1)
	{
		if(strcmp(mi.card_num, card_num) == 0)
			break;
	}

	if(feof(fp))
	{
		printf("\n卡片未注册，请联系工作人员处理！\n");
	}
	else
	{
		printf("\n尊贵的会员，您的个人信息如下：\n");
		printf("卡号：%s\n", mi.card_num);
		printf("会员ID：%u\n", mi.mid);
		printf("姓名：%s\n", mi.name);
		printf("性别：%s\n", mi.s == female ? "女" : "男");
		printf("手机号：%s\n", mi.phone);
	}

	fclose(fp);
}
